package com.hiwan.unions.application.javaScript;

import android.app.Activity;
import android.content.ActivityNotFoundException;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.content.pm.PackageManager;
import android.net.Uri;
import android.os.Bundle;
import android.text.Html;
import android.webkit.JavascriptInterface;

import com.hiwan.unions.activity.base.BaseWebView;
import com.hiwan.unions.activity.base.RootActivity;
import com.hiwan.unions.activity.loginRegister.LoginUserActivity;
import com.hiwan.unions.activity.webView.WebViewDetailedActivity;
import com.hiwan.unions.activity.webView.WebViewMapActivity;
import com.hiwan.unions.activity.webView.WebViewNoTitleActivity;
import com.hiwan.unions.application.AppManager;
import com.hiwan.unions.application.ConstantsValues;
import com.hiwan.unions.util.CheckUtils;
import com.hiwan.unions.util.interfaces.LoginInterface;
import com.yanzhenjie.nohttp.Logger;

import org.json.JSONArray;

import java.net.URISyntaxException;

/**
 * Created by JiangKang on 2016/2/19.
 */
public class AndroidJavaScript {
    Context c;
    protected SharedPreferences userInfo;
    protected SharedPreferences userInfoC;
    private LoginInterface loginInterface;
    private JSONArray jsonArray;

    public String toString() {
        return "Android";
    }

    public void setLoadingListener(LoginInterface listener) {
        this.loginInterface = listener;
    }


    public AndroidJavaScript(Context c) {
        this.c = c;
        userInfo = c.getSharedPreferences(ConstantsValues.INIT_USER_INFO, Context.MODE_PRIVATE);
        userInfoC = c.getSharedPreferences(ConstantsValues.APP, Context.MODE_PRIVATE);

    }

    //商品列表也
    @JavascriptInterface
    public void callNearDeilsActivity(String this_href, String method, String uuid) {
        Intent intent = new Intent();
        intent.setClass(c, WebViewDetailedActivity.class);
        Bundle bundle = new Bundle();
        bundle.putString("method", method);
        bundle.putString("uuid", uuid);
        bundle.putString("url", this_href);
        bundle.putBoolean("typeUUb", true);
        bundle.putBoolean("type", false);
        intent.putExtras(bundle);
        c.startActivity(intent);
    }

    //
    @JavascriptInterface
    public void createMenus(String json) {
        Logger.i("json  " + json);
        BaseWebView baseWebView = (BaseWebView) c;
        baseWebView.setTitleNa(json);

    }

    @JavascriptInterface
    public void setTypeActivity(String id, String typeName, String url) {
        Intent intent = new Intent();
        intent.setClass(c, WebViewDetailedActivity.class);
        Bundle bundle = new Bundle();
        bundle.putString("id", id);
        bundle.putString("url", url);
        bundle.putString("typeName", typeName);
        bundle.putBoolean("typeUUb", true);
        bundle.putBoolean("type", true);
        intent.putExtras(bundle);
        c.startActivity(intent);

    }

    @JavascriptInterface
    public void callNoWindWebView(String url, String method) {
        Intent intent = new Intent();
        intent.setClass(c, WebViewNoTitleActivity.class);
        Bundle bundle = new Bundle();
        bundle.putString("method", method);
        bundle.putString("url", url);
        intent.putExtras(bundle);
        c.startActivity(intent);
    }


    @JavascriptInterface
    public void callHelpDeilsActivity(String uuid, String url) {
        Intent intent = new Intent();
        intent.setClass(c, WebViewDetailedActivity.class);
        Bundle bundle = new Bundle();
        bundle.putString("method", uuid);
        bundle.putString("url", url);
        bundle.putBoolean("typeUUb", true);
        bundle.putBoolean("type", true);
        intent.putExtras(bundle);
        c.startActivity(intent);
    }

    @JavascriptInterface
    public void callHelpDeilsActivity(String uuid, String url, int i) {
        AppManager.getInstance(c).finishAllActivity(i);
        Intent intent = new Intent();
        intent.setClass(c, WebViewDetailedActivity.class);
        Bundle bundle = new Bundle();
        bundle.putString("method", uuid);
        bundle.putString("url", url);
        bundle.putBoolean("typeUUb", true);
        bundle.putBoolean("type", true);
        intent.putExtras(bundle);
        c.startActivity(intent);
    }


    //地图跳转
    @JavascriptInterface
    public void callMapActivity(String this_lat, String this_lng, String address, String this_href) {
        try {
            if (CheckUtils.isWeixinAvilible(c, "com.baidu.BaiduMap")) {
                Intent intent;
                String spStr[] = userInfoC.getString(ConstantsValues.ZUOBIAO, "").split(";");
                intent = Intent.getIntent("intent://map/direction?origin=latlng:" + spStr[0] + "," + spStr[1] + "|name:我的位置" + "&destination=latlng:" + this_lat + "," + this_lng + "|name:" + address + "&mode=driving&region=" + userInfoC.getString(ConstantsValues.CITYNAMEOne, "") + "&src=yourCompanyName|yourAppName#Intent;scheme=bdapp;package=com.baidu.BaiduMap;end");
                c.startActivity(intent); //启动调用
            } else if (CheckUtils.isWeixinAvilible(c, "com.autonavi.minimap")) {
                Intent intent;
                String spStr[] = userInfoC.getString(ConstantsValues.ZUOBIAO, "").split(";");
                intent = Intent.getIntent("androidamap://route?sourceApplication=优友宝&slat=" + spStr[0] + "&slon=" + spStr[1] + "&sname=我的位置&dlat=" + this_lat + "&dlon=" + this_lng + "&dname=" + address + "&dev=1&m=0&t=2");
                c.startActivity(intent); //启动调用
            } else {
                Intent intent = new Intent();
                intent.setClass(c, WebViewMapActivity.class);
                Bundle bundle = new Bundle();
                bundle.putString("url", this_href);
                bundle.putString("this_lat", this_lat);
                bundle.putString("this_lng", this_lng);
                intent.putExtras(bundle);
                c.startActivity(intent);
            }
        } catch (URISyntaxException e) {
            e.printStackTrace();
        }
    }

    @JavascriptInterface
    public void callGetCityName(String type) {
        RootActivity parentActivity = (RootActivity) c;
        parentActivity.cityName();
    }

    @JavascriptInterface
    public void getCityInfo() {
        Activity activity = (Activity) c;
        activity.runOnUiThread(new Runnable() {
            @Override
            public void run() {
                loginInterface.getCityInfo();
            }
        });
    }

    /**
     * toLogin  登录页面跳转
     */
    @JavascriptInterface
    public void toLogin() {
        SharedPreferences.Editor editor = userInfo.edit();
        editor.clear();
        editor.putBoolean(ConstantsValues.IS_HASLOGIN, false);
        editor.commit();
        LoginUserActivity.startPreview(c);
    }

    // 拨打电话
    @JavascriptInterface
    public void call(String phone) {
        Logger.i(" sss  " + phone);
        BaseWebView parentActivity = (BaseWebView) c;
        parentActivity.call(phone);
    }

    /**
     * 获取失败内容页面，执行
     */
    @JavascriptInterface
    public void showSource(String html) {
//        Logger.i("sss" + html);
        if (CheckUtils.containsString(html, "404") && CheckUtils.containsString(html, "Not Found") || CheckUtils.containsString(html, "403 Forbidden") || CheckUtils.containsString(html, "502 Bad") || CheckUtils.containsString(html, "Service Unavailable") || CheckUtils.containsString(html, "网页无法打开") || CheckUtils.containsString(html, "找不到网页")) {
            BaseWebView parentActivity = (BaseWebView) c;
            parentActivity.noRunb();
        } else if (Html.fromHtml(html).toString().equals("")) {
            BaseWebView parentActivity = (BaseWebView) c;
            parentActivity.noRunb();
        }
    }

    /**
     * 显示标题
     */
    @JavascriptInterface
    public void showWebNav(boolean type) {
        Logger.i("type " + type);
        loginInterface.TitleTextView(type);
    }

    /**
     * 返回执行数据
     */
    @JavascriptInterface
    public void callPlaneReturn(String para, int i) {
        BaseWebView parentActivity = (BaseWebView) c;
        parentActivity.find(para, i);
    }

    /**
     * 是否执行刷新
     */
    @JavascriptInterface
    public void shouldRefresh() {
        BaseWebView activity = (BaseWebView) c;
        activity.shuaxinWeb();
    }

    @JavascriptInterface
    public void fullscreen() {
        //监听到用户点击全屏按钮
        BaseWebView activity = (BaseWebView) c;
        activity.fullScreen();
    }

    @JavascriptInterface
    public void getInfoDetail() {
        BaseWebView activity = (BaseWebView) c;
        activity.getInfoDetail();
    }

    /**
     * 启动通讯录
     */
    @JavascriptInterface
    public void callPhone() {
        BaseWebView parentActivity = (BaseWebView) c;
        parentActivity.callPhoneArres();
    }

    /**
     * 启动通讯录
     */
    @JavascriptInterface
    public void openThirdApp(String schemeurl, String downloadurl) {
        // 判断是否安装过App，否则去市场下载
        if (isAppInstalled(schemeurl)) {
            c.startActivity(c.getPackageManager().getLaunchIntentForPackage(schemeurl));
        } else {
            goToMarket(c, schemeurl, downloadurl);
        }
    }

    /**
     * 检测某个应用是否安装
     *
     * @param packageName
     * @return
     */
    public boolean isAppInstalled(String packageName) {
        try {
            c.getPackageManager().getPackageInfo(packageName, 0);
            return true;
        } catch (PackageManager.NameNotFoundException e) {
            return false;
        }
    }

    /**
     * 去市场下载页面
     */
    public static void goToMarket(Context context, String packageName, String downloadurl) {
        try {
            Uri uri = Uri.parse("market://details?id=" + packageName);
            Intent goToMarket = new Intent(Intent.ACTION_VIEW, uri);
            context.startActivity(goToMarket);
        } catch (ActivityNotFoundException e) {
            Uri content_url = Uri.parse(downloadurl);
            Intent intent = new Intent(Intent.ACTION_VIEW, content_url);
            context.startActivity(intent);
        }
    }
}
